package com.house.keeper.service.impl;

import com.house.keeper.entity.Menu;
import com.house.keeper.entity.bean.MenuBean;
import com.house.keeper.mapper.MenuMapper;
import com.house.keeper.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zjj
 * @date 2022-05-12
 */
@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuMapper menuMapper;
    /**
     * 根据用户id查询菜单
     *
     * @param userId
     * @return
     */
    @Override
    public List<MenuBean> queryMenuByUserId(int userId) {
        List<Menu> menuList = menuMapper.queryMenuByUserId(userId);
        return getMenus(menuList,0);
    }

    /**
     * 递归查询菜单
     * @param menuList
     * @param pid
     * @return
     */
    private List<MenuBean> getMenus(List<Menu> menuList, int pid){
        List<MenuBean> sysMenuList = new ArrayList<>();
        if(menuList!=null && menuList.size()>0){
            List<MenuBean> childList = null;
            for (Menu menu:menuList) {
                if(menu.getPid()==pid){
                    if(menu.getChildCount()>0){
                        childList = getMenus(menuList,menu.getId());
                    }
                    MenuBean menuBean = new MenuBean(menu.getId(),menu.getPid(),menu.getMenuName(),menu.getMenuType(),menu.getMenuIcon(),menu.getMenuUrl(),childList);
                    sysMenuList.add(menuBean);
                    childList = null;
                }
            }
        }
        return sysMenuList;
    }


}
